package com.lw.leetcode.linked.b;

import com.lw.leetcode.linked.ListNode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * linked
 * 1019. 链表中的下一个更大节点
 *
 * @Author liw
 * @Date 2021/8/8 10:11
 * @Version 1.0
 */
public class NextLargerNodes {

    public static void main(String[] args) {
        NextLargerNodes test = new NextLargerNodes();

        ListNode node = ListNode.getInstance6();

        int[] ints = test.nextLargerNodes(node);
        System.out.println(Arrays.toString(ints));
    }

    public int[] nextLargerNodes(ListNode head) {
        int length = 0;
        ListNode item = head;
        while (item != null) {
            length++;
            item = item.next;
        }
        int[] arr = new int[length];
        int index = 0;
        while (head != null) {
            arr[index++] = head.val;
            head = head.next;
        }
        Stack<Integer> stack = new Stack<>();
        for (int i = length - 1; i >= 0; i--) {
            int value = arr[i];
            while (!stack.isEmpty() && stack.peek() <= value) {
                stack.pop();
            }
            arr[i] = stack.isEmpty() ? 0 : stack.peek();
            stack.add(value);
        }
        return arr;
    }

    public int[] nextLargerNodes2(ListNode head) {
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        int[] arr = list.stream().mapToInt(Integer::valueOf).toArray();
        int length = arr.length - 1;
        Stack<Integer> stack = new Stack<>();
        for (int i = length; i >= 0; i--) {
            int value = arr[i];
            while (!stack.isEmpty() && stack.peek() <= value) {
                stack.pop();
            }
            arr[i] = stack.isEmpty() ? 0 : stack.peek();
            stack.add(value);
        }
        return arr;
    }
}
